﻿/*
 * @author Lee 
 * Time: 20180403 
 * Abstract: SharePoint API的二次封装
 */

using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SharePointHelper.DLL.SSOM
{
	public class Service
	{
        #region 从farm中获取service
        /// <summary>
        /// 根据name从farm中获取service
        /// </summary>
        /// <param name="site"></param>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static SPService GetService(SPSite site, string serviceName)
		{
			try
			{
				if (site == null) { site = Site.GetSite(); }
				if (site == null) { throw new Exception("Failed to get SPSite from SPContext"); }

				// 获取 SPFarm
				return GetService(site.WebApplication.Farm, serviceName); 
			}
			catch (Exception ex)
			{
				Log.WriteError("xfcghjvgfydresser", ex);
			}
			return null;
		}

        /// <summary>
        /// 根据name从farm中获取service
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static SPService GetService(string serviceName)
		{
			try
			{
				SPSite site = Site.GetSite();
				if (site == null) { throw new Exception("Failed to get SPSite from SPContext"); }

				// 获取 SPFarm
				return GetService(site.WebApplication.Farm, serviceName);
			}
			catch (Exception ex)
			{
				Log.WriteError("6ygfhfgtyyt", ex);
			}
			return null;
		}


        /// <summary>
        /// 根据name从farm中获取service
        /// </summary>
        /// <param name="farm"></param>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static SPService GetService(SPFarm farm, string serviceName)
		{
			try
			{
				if (farm == null) { throw new Exception("SPFarm passed is null"); }
				if (string.IsNullOrEmpty(serviceName)) { throw new Exception("No service name passed to look up"); }


				// 获取 SPFarm
				foreach (SPService service in farm.Services)
				{
					if (String.Compare(service.Name, serviceName, true) == 0)
					{
						// 获取匹配的 service并返回
						return service;
					}
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("xfcghjvgfydresser", ex);
			}
			return null;
		}
        #endregion

        #region 获取所有farm level的services
        /// <summary>
        /// 获取所有farm level的services
        /// </summary>
        /// <param name="farm"></param>
        /// <returns></returns>
        public static List<SPService> GetAllServices(SPFarm farm)
		{
			var services = new List<SPService>();
			try
			{
				if (farm == null) { throw new Exception("SPFarm passed is null"); }


				// 获取 SPFarm
				if (farm.Services != null && farm.Services.Count > 0)
				{
					services.AddRange(farm.Services);
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("xfcghjvgfydresser", ex);
				services = null;
			}
			return services;
		}
        #endregion
    }
}
